package com.example.liuxing.jdmall.fragement;

import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.liuxing.jdmall.R;
import com.example.liuxing.jdmall.adpater.RecommendAdapter;
import com.example.liuxing.jdmall.adpater.SecoundKillAdapter;
import com.example.liuxing.jdmall.bean.Banner;
import com.example.liuxing.jdmall.bean.RGetYourFav;
import com.example.liuxing.jdmall.bean.RSecoundKill;
import com.example.liuxing.jdmall.constant.IdiyMessage;
import com.example.liuxing.jdmall.constant.NetworkConstant;
import com.example.liuxing.jdmall.controller.HomeController;
import com.example.liuxing.jdmall.listener.IModeChangeListener;
import com.example.liuxing.jdmall.ui.FixedViewUtil;
import com.example.liuxing.jdmall.ui.HorizontalListView;
import com.loopj.android.image.SmartImageView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by liuxing on 2017/7/18.
 */

public class HomeFragment extends BaseFragment implements IModeChangeListener, ViewPager.OnPageChangeListener {

    private ViewPager adViewPage;
    private AdAdapter adAdapter;
    private LinearLayout mIndicator;
    private Timer timer;
    private HorizontalListView horizonListView;
    private SecoundKillAdapter secoundKillAdapter;
    private GridView recommendGridView;
    private RecommendAdapter recommendAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initUI();
        initController();
        mController.sendAsyncMessage(IdiyMessage.GET_BANNER_ACTION, 1);
        mController.sendAsyncMessage(IdiyMessage.SECOND_KILL_ACTION, 0);
        mController.sendAsyncMessage(IdiyMessage.RECOMMEND_ACTION, 0);
    }

    @Override
    protected void initUI() {
        adViewPage = (ViewPager)getActivity().findViewById(R.id.ad_vp);
        adAdapter = new AdAdapter();
        adViewPage.setAdapter(adAdapter);
        adViewPage.addOnPageChangeListener(this);
        //  指示器
        mIndicator = (LinearLayout)getActivity().findViewById(R.id.ad_indicator);
        // 初始化横向listview
        horizonListView = (HorizontalListView)getActivity().findViewById(R.id.horizon_listView);
        secoundKillAdapter = new SecoundKillAdapter(getActivity());
        horizonListView.setAdapter(secoundKillAdapter);
        // 初始化推荐商品
        recommendGridView = (GridView)getActivity().findViewById(R.id.recommend_gv);
        recommendAdapter = new RecommendAdapter(getActivity());
        recommendGridView.setAdapter(recommendAdapter);
    }

    @Override
    protected void initController() {
        super.initController();
        mController = new HomeController(getActivity());
        mController.setIModeChangeListener(this);
    }

    @Override
    public void onModelChanged(int action, Object... valuves) {
        mHandler.obtainMessage(action, valuves[0]).sendToTarget();
    }

    @Override
    protected void handlerMessage(Message msg) {
        super.handlerMessage(msg);
        switch (msg.what) {
            case IdiyMessage.GET_BANNER_ACTION_RESULT:
                handleRusult((List<Banner>)msg.obj);
                break;
            case IdiyMessage.SECOND_KILL_ACTION_RESULT:
                handleSecondResult((ArrayList<RSecoundKill>)msg.obj);
                break;
            case IdiyMessage.RECOMMEND_ACTION_RESULT:
                handleRecommendResult((ArrayList<RGetYourFav>)msg.obj);
                break;
        }
    }

    // 推荐商品
    private void handleRecommendResult(ArrayList<RGetYourFav> datas) {
        recommendAdapter.setDatas(datas);
        recommendAdapter.notifyDataSetChanged();
        // 计算下高度
        FixedViewUtil.setListViewHeightBasedOnChildren(recommendGridView, 2);
    }

    // 秒杀的数据
    private void handleSecondResult(ArrayList<RSecoundKill> datas) {
        secoundKillAdapter.setDatas(datas);
        secoundKillAdapter.notifyDataSetChanged();
    }

    // 传入数据
    private void handleRusult(List<Banner> bannerList) {
        if (bannerList.size() != 0) {
            adAdapter.setData(bannerList);
            adAdapter.notifyDataSetChanged();
            // 设置指示器
            for (int i = 0; i < bannerList.size(); i++) {
                View view = new View(getActivity());
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
                params.setMargins(10, 0, 0, 0);
                view.setLayoutParams(params);
                view.setBackgroundResource(R.drawable.ad_indicator_bg);
                view.setEnabled(i==0);
                mIndicator.addView(view);
            }
            // 启动定时器
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    int count = adAdapter.getCount();
                    count ++;
                    /*if (count > bannerList.size() - 1) {
                        count = 0;
                    }*/
                }
            }, 3000, 3000);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        // 修改指示器样式
        int childCount = mIndicator.getChildCount();
        for (int i = 0; i < childCount; i++) {
            mIndicator.getChildAt(i).setEnabled(i == position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    // ad
    public class AdAdapter extends PagerAdapter {

        private List<Banner> datas;
        private List<SmartImageView> childViews;

        @Override
        public int getCount() {
            return datas != null? datas.size(): 0;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public void setData(List<Banner> bannerList) {
            datas = bannerList;
            childViews = new ArrayList<SmartImageView>(datas.size());
            for (Banner banner: datas) {
                SmartImageView smartView = new SmartImageView(getActivity());
                smartView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT));
                smartView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                smartView.setImageUrl(NetworkConstant.BASE_URL + banner.getAdUrl());
                childViews.add(smartView);
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            SmartImageView view = childViews.get(position);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            SmartImageView view = childViews.get(position);
            container.removeView(view);
        }
    }
}
